import React, { useState, useRef } from "react";
import { useNavigate } from "react-router-dom";

import {
  Button,
  message,
  Steps,
  Form,
  Row,
  Col,
  Input,
  Divider,
  Card,
  Result,
  Spin,
} from "antd";
import { UserOutlined, LockOutlined, SmileOutlined } from "@ant-design/icons";
import { customEmailRule, customPasswordRule } from "@/utils/validate";
import {
  getEmailCode as getEmailCodeApi,
  checkEmail as checkEmailApi,
  resetPassword as resetPasswordApi,
} from "@/api/login";
import to from "await-to-js";
const steps = [
  {
    title: "邮箱验证",
  },
  {
    title: "重置密码",
  },
  {
    title: "重置成功",
  },
];

const App: React.FC = () => {
  const [current, setCurrent] = useState(0);
  const [disabled, setDisabled] = useState(false);
  const [spinning, setSpinning] = React.useState<boolean>(false);
  // 邮箱登录参数
  const emailParams = useRef({
    email: "",
    emailCode: "",
    secretKey: "",
    password: "",
    checkPassword: "",
  });
  const [timer, setTimer] = useState(10);

  // 获取验证码按钮
  const handleGetEmailCode = async () => {
    setSpinning(true);
    const [err, res] = await to(getEmailCodeApi(emailParams.current));
    if (!err) {
      console.log(res);
      // 发送成功设置定时器
      setDisabled(true);
      setSpinning(false);

      // 自定义定时器
      const intervalID = setInterval(() => {
        setTimer((timer) => {
          if (timer === 0) {
            // 当时间到达0时，清除定时器并退出
            clearInterval(intervalID);
            setDisabled(false);
            return 10;
          }
          timer = timer - 1;
          console.log(timer);
          return timer;
        });
      }, 1000);
    } else {
      setSpinning(false);

      message.error("获取验证码失败");
    }
  };
  // 邮箱登录按钮
  const handleCheckEmailCode = async () => {
    setSpinning(true);
    console.log(emailParams.current);
    const [err, res] = await to(checkEmailApi(emailParams.current));
    if (!err) {
      console.log(res);
      emailParams.current.secretKey = res.data;
      message.success("验证成功");
      setCurrent(current + 1);
      setSpinning(false);
    } else {
      message.error("验证失败");
      setSpinning(false);
    }
  };
  // 重置按钮
  const handleReset = async () => {
    setSpinning(true);

    console.log(emailParams.current);
    if (emailParams.current.checkPassword != emailParams.current.password) {
      message.error("两次密码不一致，请检查！");
      setSpinning(false);

    } else {
      const [err, res] = await to(resetPasswordApi(emailParams.current));
      if (!err) {
        console.log(res);
        setCurrent(current + 1);
        setSpinning(false);
      } else {
        message.error("重置失败");
        setSpinning(false);
      }
    }
  };
  const navigateTo = useNavigate();

  const items = steps.map((item) => ({ key: item.title, title: item.title }));

  return (
    <>
      <Spin tip="Loading" size="large" spinning={spinning}>
        <div style={{ width: "80vw", margin: "auto" }}>
          <Steps
            current={current}
            items={items}
            style={{ marginTop: "100px" }}
          />
          <Card style={{ width: "80vw", height: "30vh", marginTop: 10 }}>
            {current === 0 && (
              <Form
                name="normal_login"
                className="login-form"
                initialValues={{ remember: false }}
                onFinish={handleCheckEmailCode}
                style={{ paddingTop: "20px", marginLeft: "370px" }}
              >
                <Form.Item
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: "请输入邮箱!",
                    },
                    { validator: customEmailRule },
                  ]}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Input
                        prefix={
                          <UserOutlined className="site-form-item-icon" />
                        }
                        onChange={(e) =>
                          (emailParams.current.email = e.target.value)
                        }
                        placeholder="邮箱"
                      />
                    </Col>
                    <Divider
                      className="h8"
                      style={{ color: "#333", marginLeft: "10px" }}
                      type="vertical"
                    />
                    <Col span={3}>
                      <Button
                        disabled={disabled}
                        style={
                          disabled
                            ? { marginLeft: "-20px" }
                            : {
                                marginLeft: "-20px",
                                color: "rgba(94, 175, 143)",
                              }
                        }
                        type="link"
                        size={"middle"}
                        onClick={handleGetEmailCode}
                      >
                        获取验证码
                        {disabled && <span>{timer}s</span>}
                      </Button>
                    </Col>
                  </Row>
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: "请输入验证码!",
                    },
                  ]}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Input
                        prefix={
                          <LockOutlined className="site-form-item-icon" />
                        }
                        type="password"
                        placeholder="验证码"
                        onChange={(e) =>
                          (emailParams.current.emailCode = e.target.value)
                        }
                      />
                    </Col>
                  </Row>
                </Form.Item>
                <Form.Item>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Button
                        type="primary"
                        htmlType="submit"
                        className="login-form-button w90"
                        // onClick={()=>handleCheckEmailCode}
                      >
                        确定
                      </Button>
                    </Col>
                  </Row>
                </Form.Item>
              </Form>
            )}
            {current === 1 && (
              <Form
                name="normal_login"
                className="login-form"
                initialValues={{ remember: false }}
                onFinish={handleReset}
                style={{ paddingTop: "20px", marginLeft: "370px" }}
              >
                <Form.Item
                  name="username"
                  rules={[
                    {
                      required: true,
                      message: "请输入新密码!",
                    },
                    { validator: customPasswordRule },
                  ]}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Input
                        prefix={
                          <UserOutlined className="site-form-item-icon" />
                        }
                        placeholder="新密码"
                        type="password"
                        onChange={(e) =>
                          (emailParams.current.password = e.target.value)
                        }
                      />
                    </Col>
                  </Row>
                </Form.Item>
                <Form.Item
                  name="password"
                  rules={[
                    {
                      required: true,
                      message: "请输入新密码!",
                    },
                  ]}
                >
                  <Row gutter={16}>
                    <Col span={12}>
                      <Input
                        prefix={
                          <LockOutlined className="site-form-item-icon" />
                        }
                        type="password"
                        placeholder="再次输入新密码"
                        onChange={(e) =>
                          (emailParams.current.checkPassword = e.target.value)
                        }
                      />
                    </Col>
                  </Row>
                </Form.Item>
                <Form.Item>
                  <Row gutter={16}>
                    <Col span={12}>
                      <Button
                        type="primary"
                        htmlType="submit"
                        className="login-form-button w90"
                      >
                        确定
                      </Button>
                    </Col>
                  </Row>
                </Form.Item>
              </Form>
            )}
            {current === 2 && (
              <Result icon={<SmileOutlined />} title="你已经重置成功" />
            )}
          </Card>
        </div>
        <div style={{ marginTop: "24px", marginLeft: "500px" }}>
          {/* {current < steps.length - 1 && (
          <Button type="primary" onClick={() => next()}>
            下一步
          </Button>
        )} */}
          {current === steps.length - 1 && (
            <Button type="primary" onClick={() => navigateTo("/")}>
              返回主页
            </Button>
          )}
          {/* {current > 0 && (
          <Button style={{ margin: "0 8px" }} onClick={() => prev()}>
            上一步
          </Button>
        )} */}
        </div>
      </Spin>
    </>
  );
};

export default App;
